<template>
  <div class="app-container">
    <vxe-grid ref="memberGridDom" v-bind="memberGridOpt" v-on="memberGridEvents">
      <template #toolbar-btns>
        <!-- <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onShowModal()">新增会员收费</vxe-button> -->
        <!-- <vxe-button status="danger" icon="vxe-icon-delete">批量删除</vxe-button> -->
      </template>
      <template #showInfo="{ row }">
        <el-button link type="primary" @click="crudStore.onShowModal(row)">查看详情</el-button>
      </template>
      <template #row-operate="{ row }">
        <!-- <el-button link type="primary" @click="crudStore.onShowModal(row)">修改</el-button> -->
        <!-- <el-button link type="danger" @click="crudStore.onDelete(row)">删除</el-button> -->
        <!-- <el-button link type="danger" @click="crudStore.onSwitchRoleEnable(row)">{row.enable ? "禁用" : "启用"}</el-button> -->
      </template>
    </vxe-grid>
    <!-- 表单 -->
    <vxe-modal ref="memberModalDom" v-bind="memberModalOpt">
      <vxe-form ref="memberFormDom" v-bind="memberFormOpt" />
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, reactive, ref } from "vue"
import { type ElMessageBoxOptions, ElMessageBox, ElMessage } from "element-plus"
import { IMember, IUserAccount, IGetMemberListDataApi, getMemberList } from "@/api/member"
import StatusSolts from "./tsx/StatusSolts.tsx"
import {
  type VxeGridInstance,
  type VxeGridProps,
  type VxeModalInstance,
  type VxeModalProps,
  type VxeFormInstance,
  type VxeFormProps,
  type VxeGridPropTypes,
  type VxeFormDefines,
  type VxeGridListeners
} from "vxe-table"

interface IRowMeta extends IUserAccount {
  /** vxe-table 自动添加上去的属性 */
  createTime: string
  createUser: Number
  updateUser: Number
  updateTime: String
  _VXE_ID?: string
}
const memberGridDom = ref<VxeGridInstance>()

const memberGridOpt: VxeGridProps = reactive({
  loading: true,
  autoResize: true,
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: [
      // {
      //   field: "scenicName",
      //   itemRender: {
      //     name: "$input",
      //     props: { placeholder: "景区名", clearable: true }
      //   }
      // },
      // {
      //   field: "scenicProvince",
      //   itemRender: {
      //     name: "$select",
      //     props: {
      //       placeholder: "所属省份",
      //       clearable: true,
      //       options: provinceList,
      //       optionProps: { value: "name", label: "name" }
      //     }
      //   }
      // },
      // {
      //   itemRender: {
      //     name: "$buttons",
      //     children: [
      //       {
      //         props: { type: "submit", content: "查询", status: "primary" }
      //       },
      //       {
      //         props: { type: "reset", content: "重置" }
      //       }
      //     ]
      //   }
      // }
    ]
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: true,
    slots: { buttons: "toolbar-btns" }
  },
  /** 自定义列配置项 */
  customConfig: {
    /** 是否允许列选中  */
    // checkMethod: ({ column }) => !["id"].includes(column.field)
  },
  /** 列配置 */
  columns: [
    {
      field: "id",
      title: "序号"
    },
    {
      field: "account",
      title: "账号"
    },
    {
      field: "invitationCode",
      title: "邀请码"
    },
    {
      field: "",
      title: "基本信息",
      slots: { default: "showInfo" }
    },
    {
      field: "createTime",
      title: "注册时间"
    },
    {
      field: "member.vipEndTime",
      title: "到期时间"
    },
    {
      field: "member",
      title: "状态",
      slots: StatusSolts
    },
    {
      field: "member.vipLevel",
      title: "vip等级"
    },
    {
      title: "操作",
      width: "150px",
      fixed: "right",
      showOverflow: false,
      slots: { default: "row-operate" }
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    // autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({ page, form }: VxeGridPropTypes.ProxyAjaxQueryParams) => {
        memberGridOpt.loading = true
        crudStore.clearTable()
        return new Promise<any>((resolve: Function) => {
          let total = 0
          let result: IRowMeta[] = []
          /** 加载数据 */
          const callback = (res: any) => {
            if (res && res.data) {
              const resData = res.data
              // 总数
              if (Number.isInteger(resData.total)) {
                total = resData.total
              }
              // 分页数据
              if (Array.isArray(resData.list)) {
                result = resData.list
              }
            }
            memberGridOpt.loading = false
            resolve({ total, result })
          }

          /** 接口需要的参数 */
          const params = {
            pageSize: page.pageSize,
            pageNum: page.currentPage
          }
          /** 调用接口 */
          getMemberList(params).then(callback).catch(callback)
        })
      }
    }
  }
})
//#endregion
//#region vxe-modal
const memberModalDom = ref<VxeModalInstance>()
const memberModalOpt: VxeModalProps = reactive({
  title: "",
  showClose: true,
  escClosable: true,
  maskClosable: true,
  beforeHideMethod: () => {
    // memberFormDom.value?.clearValidate()
    return Promise.resolve()
  }
})
//#endregion

const memberGridEvents: VxeGridListeners = {
  // cellClick({ row, column }) {
  //   if ("enable" === column.field) {
  //     crudStore.onSwitchRoleEnable(row)
  //   }
  // }
}

//#region vxe-form
const memberFormDom = ref<VxeFormInstance>()
const memberFormOpt = reactive<VxeFormProps>({
  span: 24,
  titleWidth: "100px",
  loading: false,
  /** 是否显示标题冒号 */
  titleColon: false,
  /** 表单数据 */
  data: {},
  /** 项列表 */
  items: [
    {
      field: "account",
      title: "账户名",
      itemRender: { name: "$input", props: { disabled: true } }
    },
    {
      field: "member.memberInfo",
      title: "基本信息",
      itemRender: { name: "$input", props: { disabled: true } }
    },
    {
      field: "member.businessLicense",
      title: "营业执照",
      itemRender: { name: "$input", props: { disabled: true } }
    },
    {
      field: "member.principal",
      title: "负责人",
      itemRender: { name: "$input", props: { disabled: true } }
    },
    {
      field: "member.contact",
      title: "联系方式",
      itemRender: { name: "$input", props: { disabled: true } }
    },
    {
      align: "right",
      itemRender: {
        name: "$buttons",
        children: [
          { props: { content: "取消" }, events: { click: () => memberModalDom.value?.close() } },
          {
            props: { type: "submit", content: "确定", status: "primary" },
            events: { click: () => memberModalDom.value?.close() }
          }
        ]
      }
    }
  ]
})
//#endregion

const crudStore = reactive({
  /** 表单类型：修改：true 新增：false */
  isUpdate: true,
  /** 加载表格数据 */
  commitQuery: () => memberGridDom.value?.commitProxy("query"),
  /** 清空表格数据 */
  clearTable: () => memberGridDom.value?.reloadData([]),
  /** 点击显示弹窗 */
  onShowModal: (row?: IRowMeta) => {
    if (row) {
      crudStore.isUpdate = true
      memberModalOpt.title = "基本信息"
      memberFormOpt.data = row
      // // 赋值
      // memberFormOpt.data.id = row.id
      // memberFormOpt.data.timeLimit = row.timeLimit
      // memberFormOpt.data.limitUnit = row.limitUnit
      // memberFormOpt.data.originalPrice = row.originalPrice
      // memberFormOpt.data.price = row.price
    } else {
      crudStore.isUpdate = false
      memberModalOpt.title = "新增收费"
    }
    // 禁用表单项
    // if (memberFormOpt.items) {
    //   if (memberFormOpt.items[0]?.itemRender?.props) {
    //     memberFormOpt.items[0].itemRender.props.disabled = crudStore.isUpdate
    //   }
    // }
    memberModalDom.value?.open()
    nextTick(() => {
      !crudStore.isUpdate && memberFormDom.value?.reset()
      memberFormDom.value?.clearValidate()
    })
  },
  /** 确定并保存 */
  // onSubmitForm: () => {
  //   if (memberFormOpt.loading) return
  //   memberFormDom.value?.validate((errMap?: VxeFormDefines.ValidateErrorMapParams) => {
  //     if (errMap) return
  //     memberFormOpt.loading = true
  //     const callback = (err?: any) => {
  //       memberFormOpt.loading = false
  //       if (err) return
  //       memberModalDom.value?.close()
  //       ElMessage.success("操作成功")
  //       !crudStore.isUpdate && crudStore.afterInsert()
  //       crudStore.commitQuery()
  //     }
  //     if (crudStore.isUpdate) {
  //       // 调用修改接口
  //       // const updateMemberData = {
  //       //   timeLimit: memberFormOpt.data.timeLimit,
  //       //   limitUnit: memberFormOpt.data.limitUnit,
  //       //   originalPrice: memberFormOpt.data.originalPrice,
  //       //   price: memberFormOpt.data.price
  //       // }
  //       updateMember(memberFormOpt.data.id, memberFormOpt.data)
  //         .then(() => {
  //           callback()
  //         })
  //         .catch((error) => callback(error))
  //     } else {
  //       // 调用新增接口
  //       createMember(memberFormOpt.data)
  //         .then(() => {
  //           callback()
  //         })
  //         .catch((error) => callback(error))
  //     }
  //   })
  // },
  // /** 新增后是否跳入最后一页 */
  // afterInsert: () => {
  //   const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams = memberGridDom.value?.getProxyInfo()?.pager
  //   if (pager) {
  //     const currTotal: number = pager.currentPage * pager.pageSize
  //     if (currTotal === pager.total) {
  //       ++pager.currentPage
  //     }
  //   }
  // },
  /** 删除 */
  // onDelete: (row: IRowMeta) => {
  //   const tip = `确定 <strong style='color:red;'>删除</strong> 收费项目 <strong style='color:#409eff;'></strong> ？`
  //   const config: ElMessageBoxOptions = {
  //     type: "warning",
  //     showClose: true,
  //     closeOnClickModal: true,
  //     closeOnPressEscape: true,
  //     cancelButtonText: "取消",
  //     confirmButtonText: "确定",
  //     dangerouslyUseHTMLString: true
  //   }
  //   ElMessageBox.confirm(tip, "提示", config)
  //     .then(() => {
  //       deleteMember(row.id)
  //         .then(() => {
  //           ElMessage.success("删除成功")
  //           crudStore.afterDelete()
  //           crudStore.commitQuery()
  //         })
  //         .catch(() => 1)
  //     })
  //     .catch(() => 1)
  // },
  /** 删除后是否返回上一页 */
  // afterDelete: () => {
  //   const tableData: IRowMeta[] = memberGridDom.value!.getData()
  //   const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams = memberGridDom.value?.getProxyInfo()?.pager
  //   if (pager && pager.currentPage > 1 && tableData.length === 1) {
  //     --pager.currentPage
  //   }
  // },
  /** 更多自定义方法 */
  moreFunc: () => {}
})
</script>
